package com.shizhanzhe.zxbapp.home;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.bean.YiPeople;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.Util;
import com.shizhanzhe.zxbapp.widget.ShareWxPopupWindow;
import com.superluo.textbannerlibrary.TextBannerView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class InviteFriendNewActivity extends AppCompatActivity {

    @BindView(R.id.tv_banner)
    TextBannerView tvBanner;
    @BindView(R.id.inviteDetailTv)
    TextView inviteDetailTv;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_fanscount)
    TextView tvFanscount;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.iv_ewm)
    ImageView iv_ewm;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_friend);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true, 0.2f)
                .init();
        initData();
    }

    @SuppressLint("SetTextI18n")
    private void initData() {
        tvId.setText("我的邀请码:" + UserBean.uid);
        inviteDetailTv.setText(Html.fromHtml("1、好友累计提现10元，<font color='#f12626'><b>奖励1元</b></font><br>" +
                "2、好友累计提现20元，<font color='#f12626'><b>奖励1元</b></font><br>" +
                "3、好友累计提现50元，<font color='#f12626'><b>奖励3元</b></font><br>" +
                "4、好友累计提现100元，<font color='#f12626'><b>奖励5元</b></font><br>" +
                "5、好友累计提现300元，<font color='#f12626'><b>奖励10元</b></font>"));
        iv_ewm.setImageBitmap(Util.encodeAsBitmap(Path.zxb_register(UserBean.ip, UserBean.uid)));
        inviteFriends(UserBean.uid);
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在生成...Loading");
        getTX();
    }

    @OnClick({R.id.back, R.id.tv_gotoInvite, R.id.ll_fans})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_gotoInvite:
                final ShareWxPopupWindow wxPop = new ShareWxPopupWindow(InviteFriendNewActivity.this);
                wxPop.setWxListener(new ShareWxPopupWindow.ShareWxListener() {
                    @Override
                    public void shareFriend() {
                        wxPop.dismiss();
                        dialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap = getBitmapByView(rl);
                                File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
                                if (appDir.exists()) {
                                    appDir.delete();
                                } else {
                                    appDir.mkdir();
                                }
                                File file = new File(appDir, "/invite.jpg");
                                FileOutputStream out;
                                try {
                                    out = new FileOutputStream(file);
                                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                                        out.flush();
                                        out.close();
                                        Uri uri = Uri.fromFile(file);
                                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                        Wechat.ShareParams sp = new Wechat.ShareParams();
                                        sp.setImagePath(Environment.getExternalStorageDirectory() + "/test/invite.jpg");
                                        sp.setShareType(Platform.SHARE_IMAGE);
                                        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                                        weChat.share(sp);
                                    }
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }
                        }).start();
                    }

                    @Override
                    public void shareCircle() {
                        dialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap = getBitmapByView(rl);
                                File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
                                if (appDir.exists()) {
                                    appDir.delete();
                                } else {
                                    appDir.mkdir();
                                }
                                File file = new File(appDir, "/invite.jpg");
                                FileOutputStream out;
                                try {
                                    out = new FileOutputStream(file);
                                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                                        out.flush();
                                        out.close();
                                        Uri uri = Uri.fromFile(file);
                                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                        Platform.ShareParams weM = new Platform.ShareParams();
                                        weM.setImagePath(Environment.getExternalStorageDirectory() + "/test/invite.jpg");
                                        weM.setShareType(Platform.SHARE_IMAGE);
                                        Platform WechatM = ShareSDK.getPlatform(WechatMoments.NAME);
                                        WechatM.share(weM);
                                    }
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }
                        }).start();
                    }

                    @Override
                    public void shareSave() {

                    }
                });
                wxPop.showDown2(tvId);
                break;
            case R.id.ll_fans:
                startActivity(new Intent(InviteFriendNewActivity.this, FriendDetailsActivity.class));
                break;
            default:
                break;
        }
    }

    private void inviteFriends(int uid) {
        OkHttpDownloadJsonUtil.downloadJson(InviteFriendNewActivity.this, Path.inviteFriends + "?uid=" + uid, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Gson gson = new Gson();
                    InviteFriend tiBean = gson.fromJson(json, InviteFriend.class);
                    tvFanscount.setText(tiBean.getData().size() + "");
                } else {
                    Toast.makeText(InviteFriendNewActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getTX() {
        OkHttpDownloadJsonUtil.downloadJson(InviteFriendNewActivity.this, Path.YiPeople(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        List<YiPeople.InfoBean> infoBeans = new Gson().fromJson(json, YiPeople.class).getInfo();
                        //设置数据
                        List<String> list = new ArrayList<>();
                        int price = 0;int jl = 0;
                        for (int i = 0; i < infoBeans.size(); i++) {
                            String name = infoBeans.get(i).getNickname();
                            int i1 = new Random().nextInt(5);
                            switch (i1) {
                                case 0:
                                    price = 10; jl = 1;
                                    break;
                                case 1:
                                    price = 20; jl = 1;
                                    break;
                                case 2:
                                    price = 50; jl = 3;
                                    break;
                                case 3:
                                    price = 100; jl = 5;
                                    break;
                                case 4:
                                    price = 300; jl = 10;
                                    break;
                                default:
                                    break;
                            }
                            list.add(name.length() > 5 ? name.substring(0, 5) + "…" : name + "的好友提现了" + price +"元，获得奖励" + jl + "元");
                        }
                        //调用setDatas(List<String>)方法后,TextBannerView自动开始轮播
                        //注意：此方法目前只接受List<String>类型
                        tvBanner.setDatas(list);
                    } catch (Exception e) {
                    }
                } else {
                    Toast.makeText(InviteFriendNewActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private Bitmap getBitmapByView(View headerView) {
        int h = headerView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(headerView.getWidth(), h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        headerView.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        tvBanner.startViewAnimator();
    }


    @Override
    protected void onStop() {
        super.onStop();
        tvBanner.stopViewAnimator();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
